import { ReactElement, useEffect, useState } from 'react'
import style from '../index.module.less'
import { message } from 'antd';
import { awaitWrap } from '@js/tool';
import { sendSMSRequest } from './ajax'
import { useDispatch, useSelector } from 'react-redux'
import { Dispatch } from 'redux';
import { setLoginMobile, setSendTime } from '@redux/actions/basic'
import moment from 'moment'
import { INIT_BASIC_STATE } from '../../../redux/reducers/basic';

let timer: NodeJS.Timeout;

// 验证国际区号
function validateZoneTel (zoneNum: string, zoneTelList: string[], setNoticeMobile: (v: string) => void): boolean {
  if (!zoneNum) {
    setNoticeMobile('国际区号不能为空')
    return false
  }
  if (zoneTelList.indexOf(zoneNum) === -1) {
    setNoticeMobile('国际区号不存在')
    return false
  }
  setNoticeMobile('')
  return true
}

// 验证手机号格式
function validateMobile (mobile: string, setNoticeMobile: (v: string) => void): boolean {
    if (!mobile) {
      setNoticeMobile('手机号不能为空')
      return false
    }
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      setNoticeMobile('手机号格式不正确')
      return false
    }
    setNoticeMobile('')
    return true
  }

// 发送验证码
function sendSMS (zoneTelList: string[], zoneNum: string, mobile: string, setNoticeMobile: (v: string) => void, setLoopTime: (v: number) => void, dispatch: Dispatch): void {
  if (!validateZoneTel(zoneNum, zoneTelList, setNoticeMobile) || !validateMobile(mobile, setNoticeMobile)) {
    return undefined
  }
  sendSMSHandle(mobile, dispatch)
}

async function sendSMSHandle (mobile: string, dispatch: Dispatch): Promise<void> {
  const hide = message.loading('发送中', 120)
  const [e] = await awaitWrap(sendSMSRequest(mobile))
  hide()
  if (e === null) {
    dispatch(setLoginMobile(mobile))
    dispatch(setSendTime(moment().valueOf()))
  }
}

interface Props {
  mobile: string
  zoneNum: string
  zoneTelList: string[]
  setNoticeMobile: (v: string) => void
}

function Main ({ mobile, zoneTelList, zoneNum, setNoticeMobile }: Props): ReactElement {
  const [loopTime, setLoopTime] = useState(0)
  const dispatch = useDispatch()
  const { sendTime } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      sendTime: state.basic.sendTime
    }
  })
  useEffect(() => {
    if (sendTime) {
      const time = 60 - Math.ceil((moment().valueOf() - sendTime) / 1000)
      setLoopTime(time > 0 ? time : 0)
    }
  }, [sendTime])
  useEffect(() => {
    if (loopTime > 0 && sendTime) {
      timer && clearTimeout(timer)
      timer = setTimeout(() => {
        const time = 60 - Math.ceil((moment().valueOf() - sendTime) / 1000)
        setLoopTime(time > 0 ? time : 0)
      }, 1000)
    }
  }, [loopTime])
  if (loopTime) {
    return (
      <div className={`${style['sms-btn']} ${style.disable}`}>
        <span className={style['sms-time-text']}>{loopTime}秒</span>
      </div>
    )
  } else {
    return (
      <div className={style['sms-btn']}>
        <div className={style['sms-btn-text']} onClick={() => sendSMS(zoneTelList, zoneNum, mobile, setNoticeMobile, setLoopTime, dispatch)}>
          <span>发送验证码</span>
        </div>
      </div>
    )
  }
}

export default Main
